import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:hotpot/http/interceptors/dy_error_manager.dart';
import 'package:hotpot/http/request_model.dart';
import 'package:hotpot/http/response_bean.dart';
import 'package:hotpot/odoo/odoo_helper.dart';
import 'interceptors/dy_cookie_manager.dart';

// ignore: constant_identifier_names
const TIMEOUT = Duration(milliseconds: 50000);

class HttpManager {
  static HttpManager? _instance;

  Dio get http => _dio;
  late Dio _dio;

  // 工厂和单例
  factory HttpManager() {
    return _instance ??= HttpManager._();
  }

  HttpManager._() {
    var options = BaseOptions(
      baseUrl: OdooHelper.baseurl,
      method: 'POST',
      connectTimeout: TIMEOUT,
      sendTimeout: TIMEOUT,
      receiveTimeout: TIMEOUT,
    );
    _dio = Dio(options)
      ..interceptors.add(
        LogInterceptor(
          request: false,
          requestHeader: false,
          requestBody: true,
          responseHeader: false,
          responseBody: true,
          error: true,
        ),
      )
      ..interceptors.add(DyCookieManager())
      ..interceptors.add(DyErrorManager());
  }

  Future<ResponseData> post(String path, dynamic data) async {
    if (!_dio.options.headers.containsKey(HttpHeaders.cookieHeader)) {
      _dio.options.headers[HttpHeaders.cookieHeader] = 'session_id=${OdooHelper.sessionId}';
    }
    var result = await _dio.post(path, data: formatParam(data).toJson());
    print(result.data);
    return ResponseData.fromJson(result.data);
  }

  Future<dynamic> get(String path, Map<String, dynamic> queryParameters) async {
    if (!_dio.options.headers.containsKey(HttpHeaders.cookieHeader)) {
      _dio.options.headers[HttpHeaders.cookieHeader] = 'session_id=${OdooHelper.sessionId}';
    }
    var result = await _dio.get(path, queryParameters: queryParameters);
    print(result.data);
    return result.data;
    return ResponseData.fromJson(result.data);
  }

  // 格式化参数
  static RequestModel formatParam(data) {
    return RequestModel.fromJson(data);
  }
}
